<template>
  <div class="public_height100 p20 pub_bgColorFFF">
    <div v-if="sourceType < 4" class="crumbs flex_start">
      <span class="crumbs_active" @click="goPage('layout/orderManagement')">订单管理</span>
      <img src="@/assets/img/customer/crumbs_next.png" alt="返回" class="pub_imgSize16 ml8" />
      <span class="ml8 crumbs_active" @click="goPage('layout/orderInfo')">订单信息</span>
      <img src="@/assets/img/customer/crumbs_next.png" alt="返回" class="pub_imgSize16 ml8" />
      <span class="ml8 crumbs_active " @click="goPage('layout/stockList')">库存列表</span>
      <img src="@/assets/img/customer/crumbs_next.png" alt="返回" class="pub_imgSize16 ml8" />
      <span class="ml8">添加库存</span>
    </div>
    <div v-if="sourceType >= 4" class="crumbs flex_start">
      <span class="crumbs_active " @click="goPage('layout/stockManagement')">库存列表</span>
      <img src="@/assets/img/customer/crumbs_next.png" alt="返回" class="pub_imgSize16 ml8" />
      <span class="ml8">选择产品</span>
    </div>
    <!-- ====== 左侧表单 start ======-->
    <div class="flr mt20 hc44">
      <div class="flc mr20">
        <el-form :label-width="`${$f * 100}px`" class="w550 hc32">
          <el-form-item v-if="userInfo.roleName !== '员工'" label="公司名称">
            <el-select v-model="companyParams.companyId" placeholder="请选择公司" class="pub_select" @change="getStockId">
              <el-option v-for="item in companyList" :key="item.id" :label="item.companyName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="companyParams.companyId">
            <template #label>
              <span>
                <span>库存编码</span>
                <el-tooltip content="选择公司后会自动带入库存编码" placement="top" effect="dark">
                  <i class="el-icon-question" style="color:#606266;cursor:help;" />
                </el-tooltip>
              </span>
            </template>
            <el-input v-model="addParams.productBatchNo" placeholder="选择公司后带入" disabled />
          </el-form-item>
          <el-form-item label="供应商">
            <div class="pt wp100" @click="selectSupplier">
              <el-input v-model="addParams.productSupplierName" placeholder="点击选择供应商" readonly>
                <i slot="append" class="el-icon-arrow-right fs16" />
              </el-input>
            </div>
          </el-form-item>
          <el-form-item label="品牌名称">
            <div class="pt wp100" @click="selectBrand">
              <el-input v-model="addParams.productBrandName" placeholder="点击选择品牌名称" readonly>
                <i slot="append" class="el-icon-arrow-right fs16" />
              </el-input>
            </div>
          </el-form-item>
          <el-form-item label="产品货号">
            <div class="pt wp100" @click="selectBrand">
              <el-input v-model="addParams.productBrandArticleNo" placeholder="点击选择产品货号" readonly>
                <i slot="append" class="el-icon-arrow-right fs16" />
              </el-input>
            </div>
          </el-form-item>
          <el-form-item label="规格名称">
            <div class="pt wp100" @click="selectBrand">
              <el-input v-model="addParams.productSpecificationName" placeholder="点击选择规格名称" readonly>
                <i slot="append" class="el-icon-arrow-right fs16" />
              </el-input>
            </div>
          </el-form-item>
          <el-form-item label="税号">
            <div class="pt wp100" @click="selectBrand">
              <el-input v-model="addParams.taxCode" placeholder="点击选择税号" readonly>
                <i slot="append" class="el-icon-arrow-right fs16" />
              </el-input>
            </div>
          </el-form-item>
          <el-form-item label="数量">
            <el-input v-model="addParams.qty" placeholder="请输入数量" :maxlength="6" />
          </el-form-item>
          <el-form-item label="商品单价">
            <el-input v-model="addParams.singlePrice" placeholder="请输入单价" :maxlength="8" />
          </el-form-item>
          <el-form-item label="计量单位">
            <el-select v-model="addParams.unit" placeholder="请选择计量单位" class="pub_select">
              <el-option v-for="item in unitColumns" :key="item.unit" :label="item.unit" :value="item.unit" />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="mt20 fle h32">
          <el-button type="text" class="public_e0e2e7_btn pub_button" @click="handleClose">取消</el-button>
          <el-button type="text" class="public_confirm_btn pub_button" @click="submitBtnClick"> 提交 </el-button>
        </div>
      </div>
      <div v-if="isShowSupplier" v-clickoutside.stop="supplierClickOutside" class="table_list supplierTable_list mr20 hp100">
        <div class="table_listHeader flex_space_between">
          <div class="flr" @click="isShowSupplier = false">
            <i class="el-icon-arrow-left cGR lh28 fs20" />
            <div class="mr6 pt cGR pt">收起</div>
          </div>
          <div>选择供应商</div>
          <el-button type="text" class="pub_button public_1EB398_btn" size="mini" @click="showDilogBtn('addDialogVisible')">+ 添加供应商</el-button>
        </div>
        <div class="table_search mt12">
          <el-input v-model="supplierParams.commonSearch" class="pub_input pub_input_search" placeholder="搜索供应商" clearable @keydown.enter.native="getSupplierList" @clear="getSupplierList">
            <img slot="prefix" src="@/assets/img/orderManagement/search.png" class="pub_imgSize16" />
          </el-input>
          <el-radio-group v-model="supplierParams.commonTag" size="small" class="mt10" @input="getSupplierList">
            <el-radio-button v-for="item in applyOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio-button>
          </el-radio-group>
        </div>
        <ul class="table_customerPurchaser mt16 hc208 ofya">
          <li v-for="(item, index) in supplierList" :key="index" class="flex_space_between" @click="selectedSupplier(item)">
            <div class="flex_start">
              <img v-if="item.selected === false" class="public_singImg" src="@/assets/img/orderManagement/unchecked_icon.png" />
              <img v-else class="public_singImg" src="@/assets/img/orderManagement/checked_icon.png" />
              <span class="ml5">{{ item.productSupplierName }}</span>
            </div>
            <div v-if="supplierParams.commonTag == 2" class="flex_center">
              <el-button type="text" class="pub_button public_4D5464_btn" size="mini" @click.stop="editBtnClick(item)"><i class="el-icon-edit"></i></el-button>
              <el-button type="text" class="pub_button public_4D5464_btn" size="mini" @click.stop="delBtnClick(item)"><i class="el-icon-delete"></i></el-button>
            </div>
          </li>
          <PageEmptyData v-if="supplierList.length === 0"></PageEmptyData>
        </ul>
        <div class="pub_pageination flex_start mt10 pl10 pr10">
          <el-pagination background layout="total,prev, pager, next" :page-size="supplierParams.pageSize" :current-page.sync="supplierParams.pageNum" :total="supplierParams.total" @current-change="supplierChangePage"> </el-pagination>
        </div>
      </div>
      <div v-if="isShowBrand" v-clickoutside.stop="brandClickOutside" class="wp100 flr hp100">
        <div class="table wp100 hp100 flr">
          <div class="table_list wp50">
            <div class="table_listHeader flex_space_between">
              <div class="flr" @click="isShowBrand = false">
                <i class="el-icon-arrow-left cGR lh28 fs20" />
                <div class="mr6 pt cGR pt">收起</div>
              </div>
              <div>选择品牌</div>
              <el-button type="text" class="pub_button public_1EB398_btn" size="mini" @click="showDilogBtn('addBrandDialogVisible')">+ 添加品牌</el-button>
            </div>
            <div class="table_search mt12">
              <el-input v-model="brandParams.commonSearch" class="pub_input pub_input_search" placeholder="搜索品牌" clearable @keydown.enter.native="brandHandleSearch" @clear="brandHandleSearch">
                <img slot="prefix" src="@/assets/img/orderManagement/search.png" class="pub_imgSize16" />
              </el-input>
              <el-radio-group v-model="brandParams.commonTag" size="small" class="mt10" @input="getBrandList">
                <el-radio-button v-for="item in applyOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio-button>
              </el-radio-group>
            </div>
            <ul class="table_customer mt16 hc208 ofya">
              <li v-for="(item, index) in brandList" :key="index" class="flex_space_between" :class="[item.selected ? 'active' : '']" @click="selectedBrand(item)">
                <span class="ml5">{{ item.productBrandName }}</span>
                <div v-if="brandParams.commonTag == 2" class="flex_center table_group">
                  <el-button type="text" class="pub_button public_4D5464_btn" size="mini" @click.stop="editBrandBtnClick(item)"><i class="el-icon-edit"></i></el-button>
                  <el-button type="text" class="pub_button public_4D5464_btn" size="mini" @click.stop="delBrandBtnClick(item)"><i class="el-icon-delete"></i></el-button>
                </div>
              </li>
              <PageEmptyData v-if="brandList.length === 0"></PageEmptyData>
            </ul>
            <div v-if="brandList.length > 0" class="pub_pageination flex_start mt10 pl10 pr10">
              <el-pagination background layout="total,prev, pager, next" :page-size="brandParams.pageSize" :current-page.sync="brandParams.pageNum" :total="brandParams.total" @current-change="brandChangePage"> </el-pagination>
            </div>
          </div>
          <div class="table_list wp50">
            <div class="table_listHeader flex_space_between">
              <span>选择产品</span>
              <el-button type="text" class="pub_button public_1EB398_btn" size="mini" @click="showDilogBtn('addProdcutDialogVisible')">+ 添加产品</el-button>
            </div>
            <div class="table_search mt12">
              <el-input v-model="productParams.commonSearch" class="pub_input pub_input_search" placeholder="搜索货号、产品名称" clearable @keydown.enter.native="productHandleSearch" @clear="productHandleSearch">
                <img slot="prefix" src="@/assets/img/orderManagement/search.png" class="pub_imgSize16" />
              </el-input>
              <el-radio-group v-if="brandParams.commonTag == 1" v-model="productParams.commonTag" size="small" class="mt10" @input="resetProductParams">
                <el-radio-button v-for="item in applyOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio-button>
              </el-radio-group>
            </div>
            <ul class="table_customerPurchaser mt16 hc208 ofya">
              <li v-for="(item, index) in productList" :key="index" class="flex_space_between" @click="selectedProduct(item)">
                <div class="flex_start2">
                  <img v-if="item.selected === false" class="public_singImg" src="@/assets/img/orderManagement/unchecked_icon.png" />
                  <img v-else class="public_singImg" src="@/assets/img/orderManagement/checked_icon.png" />
                  <div class="flex_center_columnStart purchaser_info ml5">
                    <div class="purchaserName">
                      <span>{{ item.productBrandArticleNoName }}</span>
                    </div>
                    <div class="purchaserPhone mt5">
                      <span>货号：{{ item.productBrandArticleNo }}</span>
                    </div>
                    <div class="purchaserPhone mt5">
                      <span>规格：{{ item.productSpecificationName }}</span>
                    </div>
                    <div class="purchaserPhone mt5">
                      <span>税收编码：{{ item.taxCode }}</span>
                    </div>
                  </div>
                </div>
                <div v-if="productParams.commonTag == 2" class="flex_center ">
                  <el-button type="text" class="pub_button public_4D5464_btn" size="mini" @click.stop="editProdcutBtnClick(item)"><i class="el-icon-edit"></i></el-button>
                  <el-button type="text" class="pub_button public_4D5464_btn" size="mini" @click.stop="delBrandBtnClick(item)"><i class="el-icon-delete"></i></el-button>
                </div>
              </li>
              <PageEmptyData v-if="productList.length === 0"></PageEmptyData>
            </ul>
            <div v-if="productList.length > 0" class="pub_pageination flex_start mt10 pl10 pr10">
              <el-pagination :pager-count="5" background layout="total,prev, pager, next" :page-size="productParams.pageSize" :current-page.sync="productParams.pageNum" :total="productParams.total" @current-change="productChangePage"> </el-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- ====== 表格上方的筛选条件 end ======-->
    <!-- 删除提示 -->
    <deleteDialog :multiple-selection="multipleSelection" :visible="deleteDialogVisible" @close="closeDialog" @submit="confirmDelete" />
    <!-- 添加供应商 -->
    <PageDialog :title="addSupplierParams.id ? '编辑供应商' : '添加供应商'" :dialog-visible="addDialogVisible" :width="`${$f * 600}px`" @close="closeDialog" @submit="confirmAdd">
      <el-form ref="supplierRuleForm" :model="addSupplierParams" :rules="rules" label-width="5rem" class="addOrder">
        <el-form-item label="供应商" prop="productSupplierName">
          <el-input v-model="addSupplierParams.productSupplierName" placeholder="请输入供应商" class="pub_input" :maxlength="10" />
        </el-form-item>
      </el-form>
    </PageDialog>
    <!-- 新增品牌 -->
    <PageDialog :title="addBrandParams.id ? '编辑品牌' : '新增品牌'" :dialog-visible="addBrandDialogVisible" :width="`${$f * 600}px`" @close="closeDialog" @submit="confirmBrandAdd">
      <el-form ref="brandRuleForm" :model="addBrandParams" :rules="brandRules" label-width="5.625rem" class="pub_form_item">
        <el-form-item label="品牌名称" prop="productBrandName">
          <el-input v-model="addBrandParams.productBrandName" placeholder="请输入品牌名称" class="pub_input" :maxlength="10" />
        </el-form-item>
      </el-form>
    </PageDialog>
    <PageDialog :title="'库存编码说明'" :dialog-visible="stockCodeDialogVisible" :width="`${$f * 600}px`" :show-footer="false" @close="closeDialog">
      <div class="fs16 flc">
        <span>一.库存编码自动生成，前两位是公司编码，后六位是自增的编码;</span>
        <span>二.库存编码唯一确定一个库存产品，哪怕所有信息都一样，只要库存编码不一样就算不同的库存；</span>
      </div>
    </PageDialog>
    <!-- 删除品牌提示 -->
    <deleteDialog :multiple-selection="multipleSelection" :visible="deleteBrandDialogVisible" @close="closeDialog" @submit="confirmBrandDelete" />
    <!-- 添加产品 -->
    <PageDialog :title="addProductParams.id ? '编辑产品' : '添加产品'" :dialog-visible="addProdcutDialogVisible" :width="`${$f * 600}px`" @close="closeDialog" @submit="confirmAddProduct">
      <el-form ref="productRuleForm" :model="addProductParams" :rules="productRules" label-width="5.625rem" class="pub_form_item">
        <el-form-item label="产品货号" prop="productBrandArticleNo">
          <el-input v-model="addProductParams.productBrandArticleNo" placeholder="请输入货号" class="pub_input" :maxlength="15" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productBrandArticleNoName">
          <el-input v-model="addProductParams.productBrandArticleNoName" placeholder="请输入产品名称" class="pub_input" :maxlength="500" />
        </el-form-item>
        <el-form-item label="税收编码" prop="taxCode">
          <el-select v-model="addProductParams.taxCode" placeholder="请选择税收编码" class="pub_select">
            <el-option v-for="(item, index) in taxCodeColumns" :key="index" :label="item.taxCode" :value="item.taxCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="productSpecificationName">
          <scroll-select v-model="addProductParams.productSpecificationName" placeholder="输入规格名称搜索" :remote-method="fetchSpecification" label-key="username" value-key="id" />
        </el-form-item>
      </el-form>
    </PageDialog>
    <!-- 删除商品提示 -->
    <deleteDialog :multiple-selection="multipleSelection" :visible="deleteProductDialogVisible" @close="closeDialog" @submit="confirmDeleteProduct" />
  </div>
</template>
<script>
import { debounce } from '@/utils/debounce';
import PageEmptyData from '@/components/PageEmptyData/index.vue';
import PageDialog from '@/components/PageDialog/index.vue';
import deleteDialog from '@/components/deleteDialog.vue';
import scrollSelect from '@/components/scrollSelect.vue';
import clickoutside from 'element-ui/src/utils/clickoutside';
export default {
  components: { scrollSelect, PageEmptyData, PageDialog, deleteDialog },
  directives: { clickoutside },
  data() {
    return {
      stockCodeDialogVisible: false,
      applyOptions: [{ value: 1, label: '公共' }],
      companyParams: { companyId: '', productBatchNo: '' },
      deleteDialogVisible: false,
      addDialogVisible: false,
      addSupplierParams: { productSupplierName: '' }, //添加供应商参数
      // 供应商表单验证规则
      rules: {
        productSupplierName: [
          { required: true, message: '请输入供应商名称', trigger: 'blur' },
          { max: 10, message: '供应商名称不能超过10个字符', trigger: 'blur' }
        ]
      },
      // 品牌表单验证规则
      brandRules: {
        productBrandName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { max: 10, message: '品牌名称不能超过10个字符', trigger: 'blur' }
        ]
      },
      // 产品表单验证规则
      productRules: {
        productBrandArticleNo: [
          { required: true, message: '请输入产品货号', trigger: 'blur' },
          { max: 15, message: '产品货号不能超过15个字符', trigger: 'blur' }
        ],
        productBrandArticleNoName: [
          { required: true, message: '请输入产品名称', trigger: 'blur' },
          { max: 500, message: '产品名称不能超过500个字符', trigger: 'blur' }
        ],
        taxCode: [{ required: true, message: '请选择税收编码', trigger: 'change' }],
        productSpecificationName: [{ required: true, message: '请选择规格', trigger: 'change' }]
      },
      supplierParams: { commonSearch: '', commonTag: 1, total: 0, pageSize: 20, pageNum: 1 }, //搜索供应商
      deleteBrandDialogVisible: false,
      addBrandDialogVisible: false,
      addBrandParams: { productBrandName: '' }, //新增品牌参数
      addProdcutDialogVisible: false,
      deleteProductDialogVisible: false,
      isShowSupplier: false,
      isShowBrand: false,
      addProductParams: {
        //添加产品参数
        productBrandArticleNo: '', //货号
        productBrandArticleNoName: '', //名称
        taxCode: '', //税收编码
        productSpecificationName: '' //规格
      },
      taxCodeColumns: [
        //税收编码
        { taxCode: '生物化学制品-1070307000000000000' },
        { taxCode: '化学原料及化学制品-1070200000000000000' },
        { taxCode: '橡胶制品-1070500000000000000' },
        { taxCode: '塑料制品-1070601000000000000' },
        { taxCode: '玻璃制品-1080110000000000000' },
        { taxCode: '纸及纸制品-1060100000000000000' },
        { taxCode: '金属制品-1080400000000000000' },
        { taxCode: '技术陶瓷制品-1080120000000000000' },
        { taxCode: '分析仪器及装置-1090605000000000000' },
        { taxCode: '绘图、计算及测量仪器-1090604000000000000' },
        { taxCode: '软件产品-1060301000000000000' },
        { taxCode: '研发和技术服务-3040100000000000000' },
        { taxCode: '文具及类似用品-1060401000000000000' }
      ],
      multipleSelection: [], //选中的表格数据
      selectedRow: {}, //当前选择的数据
      addParams: { qty: '', unit: '', singlePrice: '', productBrandName: '' },
      unitColumns: [], //计量单位
      supplierListOrg: [],
      supplierList: [], //供应商列表
      brandParams: { commonTag: 1, commonSearch: '', total: 0, pageSize: 20, pageNum: 1 }, //搜索品牌参数
      brandList: [], //品牌列表
      productParams: { commonTag: 1, productBrandName: '', commonSearch: '', total: 0, pageSize: 20, pageNum: 1 },
      productList: [], //产品列表
      companyList: [],
      sourceType: null //1：新增订单 2：编辑 3：查看详情 4:库存管理页面新增库存 5、库存管理页面编辑库存
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.userInfo;
    },
    roleType() {
      //1:超级管理员 2:普通管理员 3:普通员工
      return this.$store.state.userInfo.roleType;
    }
  },
  async created() {
    if (this.roleType != 1) {
      this.applyOptions.push({ value: 2, label: '自建' });
    }
    this.sourceType = this.$route.query.sourceType * 1;
    this.getSupplierList();
    this.getBrandList();
    await this.getCompanyList();
    this.getUnitAll();
    if (this.userInfo.roleName === '员工') {
      this.getStockId(this.userInfo.companyId);
      this.companyParams.companyId = this.userInfo.companyId;
    }
  },
  methods: {
    //获取公司列表
    async getCompanyList() {
      let { data } = await this.$api.get(this.$url.companyAll);
      this.companyList = data;
    },
    async getUnitAll() {
      let { data } = await this.$api.get(this.$url.unitAll);
      this.unitColumns = data;
    },
    //供应商列表
    async getSupplierList() {
      let res = await this.$api.get(this.$url.productSupplierList, this.supplierParams);
      res.rows.forEach(el => {
        el.selected = false;
      });
      this.supplierList = res.rows;
      this.supplierParams.total = res.total;
    },
    //修改供应商页码
    supplierChangePage(pageNum) {
      this.brandParams.pageNum = pageNum;
      this.getSupplierList();
    },
    //点击供应商弹框外部
    supplierClickOutside() {
      // 当添加供应商弹框打开时，不关闭供应商选择区域
      if (this.isShowSupplier && !this.addDialogVisible) {
        this.isShowSupplier = false;
      }
    },
    //选择供应商
    selectedSupplier(row) {
      this.supplierList.forEach(item => {
        item.selected = false;
      });
      row.selected = true;
      this.addParams.productSupplierName = row.productSupplierName;
    },
    //点击品牌弹框外部
    brandClickOutside() {
      // 当添加品牌或添加产品弹框打开时，不关闭品牌选择区域
      if (this.isShowBrand && !this.addBrandDialogVisible && !this.addProdcutDialogVisible) {
        this.isShowBrand = false;
      }
    },
    //获取品牌数据
    async getBrandList() {
      let res = await this.$api.get(this.$url.productBrandAll, this.brandParams);
      res.rows.forEach((el, index) => {
        el.selected = false;
      });
      this.brandList = res.rows;
      this.brandParams.total = res.total;
      if (this.brandList.length > 0) {
        this.productParams = { ...this.productParams, commonSearch: '' };
        this.productParams.commonTag = this.brandParams.commonTag;
        this.resetProductParams();
      }
    },
    //搜索品牌
    brandHandleSearch() {
      this.brandParams.pageNum = 1;
      this.brandParams.pageSize = 10;
      this.getBrandList();
    },
    //选择品牌
    selectedBrand(row) {
      this.brandList.forEach(item => {
        item.selected = false;
      });
      row.selected = true;
      this.addParams.productBrandName = row.productBrandName;
      this.productParams = { ...this.productParams, commonSearch: '', productBrandName: row.productBrandName };
      this.resetProductParams();
    },
    //修改页码
    brandChangePage(pageNum) {
      this.brandParams.pageNum = pageNum;
      this.getBrandList();
    },
    //获取产品列表
    async getProductAll() {
      let res = await this.$api.get(this.$url.productAll, this.productParams);
      res.rows.forEach((val, index) => {
        val.selected = false;
      });
      this.productList = res.rows;
      this.productParams.total = res.total;
    },
    selectedCustomer(row) {
      this.companyList.forEach((item, index) => {
        item.selected = item.id === row.id;
      });
    },
    //选择产品
    selectedProduct(row) {
      this.productList.forEach(item => {
        item.selected = false;
      });
      row.selected = true;
      this.addParams.productBrandArticleNo = row.productBrandArticleNo;
      this.addParams.productSpecificationName = row.productSpecificationName;
      this.addParams.taxCode = row.taxCode;
    },
    //搜索产品
    productHandleSearch() {
      this.productParams.pageNum = 1;
      this.productParams.pageSize = 10;
      this.getProductAll();
    },
    //重置产品参数
    resetProductParams() {
      this.productList = [];
      this.productParams.pageNum = 1;
      this.getProductAll();
    },
    //修改页码
    productChangePage(pageNum) {
      this.productParams.pageNum = pageNum;
      this.resetProductParams();
    },
    //页面跳转
    goPage(pageUrl) {
      this.$router.push({ path: '/' + pageUrl, query: { sourceType: this.sourceType, activeIndex: this.sourceType < 4 ? '1' : '3' } });
    },
    //确认
    submitBtnClick: debounce(async function() {
      let companyInfo = this.companyList.find(item => item.id === this.companyParams.companyId); //公司信息
      let supplierInfo = this.supplierList.find(item => item.selected);
      let brandInfo = this.brandList.find(item => item.selected);
      let productInfo = this.productList.find(item => item.selected);
      const { qty, unit, singlePrice } = this.addParams;
      if (!companyInfo) {
        return this.$message.warning('请选择公司');
      }
      if (!supplierInfo) {
        return this.$message.warning('请选择供应商');
      }
      if (!productInfo) {
        return this.$message.warning('请选择产品');
      }
      if (!qty) {
        return this.$message.warning('请输入库存数量');
      }
      if (!singlePrice) {
        return this.$message.warning('请输入单价');
      }
      if (!unit) {
        return this.$message.warning('请选择计量单位');
      }
      this.addParams = { ...this.addParams, ...companyInfo, ...supplierInfo, ...brandInfo, ...productInfo, companyId: companyInfo.id };
      let res = await this.$api.post(this.$url.inventoryAdd, this.addParams);
      if (res.code === 200) {
        this.$message.success('新增成功');
        this.handleClose();
      }
    }, 500),
    handleClose() {
      this.goPage(this.sourceType < 4 ? 'layout/stockList' : 'layout/stockManagement');
    },
    //显示供应商弹框
    selectSupplier() {
      this.isShowSupplier = true;
    },
    //编辑供应商
    editBtnClick(item) {
      this.addSupplierParams = Object.assign({}, item);
      this.showDilogBtn('addDialogVisible');
    },
    //删除供应商
    delBtnClick(val) {
      this.selectedRow = JSON.parse(JSON.stringify(val));
      this.showDilogBtn('deleteDialogVisible');
    },
    //显示弹窗
    showDilogBtn(field) {
      this[field] = !this[field];
    },
    //关闭弹窗
    closeDialog() {
      this.addProdcutDialogVisible = false;
      this.selectedRow = null;
      this.multipleSelection = [];
      this.stockCodeDialogVisible = false;
      this.addDialogVisible = false;
      this.deleteDialogVisible = false;
      this.addBrandDialogVisible = false;
      this.deleteBrandDialogVisible = false;
      this.deleteProductDialogVisible = false;
      this.addProductParams = Object.assign({}, this.$options.data().addProductParams); //重置参数
      this.addBrandParams = Object.assign({}, this.$options.data().addBrandParams); //重置参数
      this.addSupplierParams = Object.assign({}, this.$options.data().addSupplierParams); //重置参数
    },
    //确认删除供应商
    async confirmDelete() {
      let res = null;
      if (this.multipleSelection.length > 0 && this.selectedRow === null) {
        let idArr = this.multipleSelection.map(val => val.id);
        res = await this.$api.post(this.$url.productSupplierDeleteBatch, idArr);
      } else {
        res = await this.$api.post(this.$url.productSupplierDelete, { id: this.selectedRow.id });
      }
      this.closeDialog();
      if (res.code === 200) {
        this.$message.success('删除成功');
        this.getSupplierList();
      } else {
        this.$message.success('删除失败');
      }
    },
    //确认添加供应商
    async confirmAdd() {
      this.$refs.supplierRuleForm.validate(async valid => {
        if (valid) {
          let { id } = this.addSupplierParams;
          let url = id ? this.$url.productSupplierUpdate : this.$url.productSupplierAdd;
          let res = await this.$api.post(url, this.addSupplierParams);
          if (res.code === 200) {
            this.closeDialog();
            this.getSupplierList();
            this.$message.success(id ? '更新成功' : '新增成功');
          }
        }
      });
    },
    //显示品牌弹框
    selectBrand() {
      this.isShowBrand = true;
    },
    //确认添加品牌
    async confirmBrandAdd() {
      this.$refs.brandRuleForm.validate(async valid => {
        if (valid) {
          let { id } = this.addBrandParams;
          let url = id ? this.$url.productBrandUpdate : this.$url.productBrandAdd;
          let res = await this.$api.post(url, this.addBrandParams);
          if (res.code === 200) {
            this.closeDialog();
            this.getBrandList();
            this.$message.success(id ? '更新成功' : '新增成功');
          }
        }
      });
    },
    async fetchSpecification(params) {
      let res = await this.$api.get(this.$url.productSpecificationAll, params);
      return res;
    },
    //添加产品
    async confirmAddProduct() {
      this.$refs.productRuleForm.validate(async valid => {
        if (valid) {
          let { id } = this.addProductParams;
          let url = id ? this.$url.productUpdate : this.$url.productAdd;
          this.addProductParams.productBrandName = this.productParams.productBrandName;
          let res = await this.$api.post(url, this.addProductParams);
          if (res.code === 200) {
            this.closeDialog();
            this.resetProductParams();
            this.$message.success(id ? '更新成功' : '新增成功');
          }
        }
      });
    },
    //编辑产品
    editProdcutBtnClick(item) {
      this.addProductParams = Object.assign({}, item);
      this.addProdcutDialogVisible = true;
    },
    //编辑品牌
    editBrandBtnClick(row) {
      this.addBrandParams = Object.assign({}, row);
      this.showDilogBtn('addBrandDialogVisible');
    },
    //删除品牌
    delBrandBtnClick(row) {
      this.selectedRow = JSON.parse(JSON.stringify(row));
      this.showDilogBtn('deleteBrandDialogVisible');
    },
    //确认删除品牌
    async confirmBrandDelete() {
      let res = null;
      if (this.multipleSelection.length > 0 && this.selectedRow === null) {
        let idArr = this.multipleSelection.map(val => val.id);
        res = await this.$api.post(this.$url.productBrandDeleteBatch, idArr);
      } else {
        res = await this.$api.post(this.$url.productBrandDelete, { id: this.selectedRow.id });
      }
      if (res.code === 200) {
        this.$message.success('删除成功');
        this.getBrandList();
        this.closeDialog();
      } else {
        this.$message.success('删除失败');
      }
    },
    //确认删除商品
    async confirmDeleteProduct() {
      let res = null;
      if (this.multipleSelection.length > 0 && this.selectedProuctRow === null) {
        let idArr = this.multipleSelection.map(val => val.id);
        res = await this.$api.post(this.$url.productBrandArticleNoDeleteBatch, idArr);
      } else {
        res = await this.$api.post(this.$url.productDelete, { id: this.selectedProuctRow.id });
      }
      if (res.code === 200) {
        this.resetProductParams();
        this.closedeleteProductDialog();
        this.$message.success('删除成功');
      } else {
        this.$message.success('删除失败');
      }
    },
    //获取库存编码
    async getStockId(companyId) {
      let idx = this.companyList.findIndex(el => el.id === companyId);
      let companyCode = this.companyList[idx].companyCode;
      let res = await this.$api.get(this.$url.getInventoryList, { companyId });
      if (res.data.length === 0) {
        this.$set(this.addParams, 'productBatchNo', `${companyCode}000001`);
      } else {
        let no = this.incrementNoString(res.data[res.data.length - 1]);
        this.$set(this.addParams, 'productBatchNo', no);
      }
    },
    incrementNoString(str) {
      // 验证输入
      if (typeof str !== 'string' || str.length !== 8) {
        throw new Error('输入必须是长度为8的字符串');
      }
      const prefix = str.substring(0, 2); // 提取前4位
      const numPart = str.substring(2); // 提取后8位数字
      // 验证后6位是否为纯数字
      // eslint-disable-next-line
      if (!/^\d{6}$/.test(numPart)) {
        throw new Error('字符串后6位必须是数字');
      }
      // 数字加1并处理进位
      let num = parseInt(numPart, 10) + 1;
      // 处理99999999+1的进位情况（取模防止溢出）
      const newNum = num
        .toString()
        .padStart(6, '0')
        .slice(-6);
      return prefix + newNum;
    }
  }
};
</script>
<style lang="less" scoped>
.table_filter_title {
  font-size: 16px;
  color: #0a0b0d;
}
.table_list.supplierTable_list {
  width: 528px;
  border: 1px solid #e0e2e7;
}
.table {
  border: 1px solid #e0e2e7;
}
.table_filter_search {
  width: 400px;
}
.table_list {
  & + .table_list {
    border-left: 1px solid #e0e2e7;
    box-sizing: border-box;
  }
  .table_listHeader {
    height: 48px;
    background: #f4f5f6;
    border-radius: 0px 0px 0px 0px;
    padding: 14px;
    font-size: 14px;
    color: #4d5464;
    box-sizing: border-box;
  }
  .table_customer,
  .table_search {
    width: 100%;
    padding: 0px 12px;
    box-sizing: border-box;
  }
  .table_customerPurchaser li,
  .table_customer > li {
    width: 100%;
    box-sizing: border-box;
    padding: 12px 16px;
    font-size: 14px;
    cursor: pointer;
  }
  .table_customer > li {
    color: #4d5464;
    border-left: 3px solid #fff;
    &.active,
    &:hover {
      background: #f4f5f6;
      border-left: 3px solid #1eb398;
    }
    &.active {
      .table_group {
        display: flex;
      }
    }
    .table_group {
      display: none;
    }
  }
  .table_customerPurchaser li {
    img {
      width: 20px;
      height: 20px;
    }
    .nameBox {
      height: 37px;
    }
    .nameBox {
      width: 37px;
      background: rgba(39, 193, 165, 0.1);
      border-radius: 50%;
      border: 1px solid rgba(39, 193, 165, 0.1);
      font-size: 12px;
      color: #1eb398;
      font-weight: 600;
    }
    .purchaserName {
      font-weight: 500;
      font-size: 14px;
      font-weight: 600;
    }
    .purchaserPhone {
      font-size: 12px;
      color: #667085;
    }
    .purchaser_info.flex_center_columnStart {
      justify-content: space-between;
    }
  }
}
</style>
